package com.tiktok.controller;

import com.tiktok.dto.Result;
import com.tiktok.dto.request.LoginRequest;
import com.tiktok.dto.request.RegisterRequest;
import com.tiktok.entity.User;
import com.tiktok.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@Validated @RequestBody RegisterRequest request) {
        userService.register(request);
        return Result.success("注册成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Validated @RequestBody LoginRequest request) {
        String token = userService.login(request);
        
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("tokenType", "Bearer");
        
        return Result.success("登录成功", data);
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        // 由于使用JWT token，注销主要由客户端处理（删除本地token）
        // 服务端可以记录注销日志或进行其他清理操作
        return Result.success("注销成功");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/profile")
    public Result<User> getCurrentUser() {
        User user = userService.getCurrentUser();
        if (user != null) {
            // 隐藏密码
            user.setPassword(null);
        }
        return Result.success(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public Result<String> updateProfile(@RequestBody User user) {
        User currentUser = userService.getCurrentUser();
        if (currentUser == null) {
            return Result.unauthorized();
        }
        
        // 只允许更新部分字段
        currentUser.setNickname(user.getNickname());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhone(user.getPhone());
        currentUser.setAvatar(user.getAvatar());
        currentUser.setGender(user.getGender());
        currentUser.setBirthday(user.getBirthday());
        currentUser.setSignature(user.getSignature());
        
        userService.updateById(currentUser);
        return Result.success("更新成功");
    }
} 